﻿using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.AutoMapper;
using Abp.Domain.Repositories;
using Abp.Linq.Extensions;
using Abp.UI;
using KDS.Mes.Authorization;
using KDS.Mes.Dto;
using KDS.Mes.Mes.Cartypes.Dtos;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;

namespace KDS.Mes.Mes.Cartypes
{
    /// <summary>
    /// 车型信息服务实现
    /// </summary>s
    [AbpAuthorize(AppPermissions.Pages_Bom_Cartypes)]
    public class CartypeAppService : MesAppServiceBase, ICartypeAppService
    {
        private readonly IRepository<Cartype, int> _cartypeRepository;
        private readonly ICartypeListExcelExporter _cartypeListExcelExporter;

        private readonly CartypeManage _cartypeManage;

        /// <summary>
        /// 构造方法
        /// </summary>
        public CartypeAppService(
            IRepository<Cartype, int> cartypeRepository,
            CartypeManage cartypeManage,
            ICartypeListExcelExporter cartypeListExcelExporter
        )
        {
            _cartypeRepository = cartypeRepository;
            _cartypeManage = cartypeManage;
            _cartypeListExcelExporter = cartypeListExcelExporter;
        }

        #region 车型信息管理

        public async Task<ListResultDto<CartypeListDto>> GetCartypes(GetCartypeInput input)
        {
            var cartypes = await _cartypeRepository.GetAll()
                .ToListAsync();

            return new ListResultDto<CartypeListDto>(cartypes.MapTo<List<CartypeListDto>>());
        }


        /// <summary>
        /// 根据查询条件获取车型信息分页列表
        /// </summary>
        public async Task<PagedResultDto<CartypeListDto>> GetPagedCartypesAsync(GetCartypeInput input)
        {
            var query = _cartypeRepository.GetAll();
            //TODO:根据传入的参数添加过滤条件

            var cartypeCount = await query.CountAsync();

            var cartypes = await query
            .OrderBy(input.Sorting)
            .PageBy(input)
            .ToListAsync();

            var cartypeListDtos = cartypes.MapTo<List<CartypeListDto>>();
            return new PagedResultDto<CartypeListDto>(
            cartypeCount,
            cartypeListDtos
            );
        }

        public PagedResultDto<CartypeListDto> GetPagedCartypes(GetCartypeInput input)
        {
            //初步过滤
            var query = _cartypeRepository.GetAll();
            //排序
            query = !string.IsNullOrEmpty(input.Sorting) ? query.OrderBy(x => x.Id) : query.OrderByDescending(t => t.CreationTime);
            //获取总数
            var tasksCount = query.Count();
            //默认的分页方式
            //var taskList = query.Skip(input.SkipCount).Take(input.MaxResultCount).ToList();
            //ABP提供了扩展方法PageBy分页方式
            var taskList = query.PageBy(input).ToList();
            return new PagedResultDto<CartypeListDto>(tasksCount, taskList.MapTo<List<CartypeListDto>>());
        }

        /// <summary>
        /// 通过Id获取车型信息信息进行编辑或修改
        /// </summary>
        public async Task<GetCartypeForEditOutput> GetCartypeForEditAsync(NullableIdDto<int> input)
        {
            var output = new GetCartypeForEditOutput();

            CartypeEditDto cartypeEditDto;

            if (input.Id.HasValue)
            {
                var entity = await _cartypeRepository.GetAsync(input.Id.Value);
                cartypeEditDto = entity.MapTo<CartypeEditDto>();
            }
            else
            {
                cartypeEditDto = new CartypeEditDto();
            }

            output.Cartype = cartypeEditDto;
            return output;
        }

        /// <summary>
        /// 通过指定id获取车型信息ListDto信息
        /// </summary>
        public async Task<CartypeListDto> GetCartypeByIdAsync(EntityDto<int> input)
        {
            var entity = await _cartypeRepository.GetAsync(input.Id);

            return entity.MapTo<CartypeListDto>();
        }

        /// <summary>
        /// 新增或更改车型信息
        /// </summary>
        public async Task CreateOrUpdateCartypeAsync(CreateOrUpdateCartypeInput input)
        {
            if (input.CartypeEditDto.Id.HasValue)
            {
                await UpdateCartypeAsync(input.CartypeEditDto);
            }
            else
            {
                await CreateCartypeAsync(input.CartypeEditDto);
            }
        }

        /// <summary>
        /// 新增车型信息
        /// </summary>
        [AbpAuthorize(AppPermissions.Pages_Bom_Cartypes_Create)]
        public virtual async Task<CartypeEditDto> CreateCartypeAsync(CartypeEditDto input)
        {
            //TODO:新增前的逻辑判断，是否允许新增
            await CheckCartypeIfAlreadyExists(input.CartypeName, input.CartypeCode, input.Id);
            var entity = input.MapTo<Cartype>();

            entity = await _cartypeRepository.InsertAsync(entity);
            return entity.MapTo<CartypeEditDto>();
        }

        /// <summary>
        /// 编辑车型信息
        /// </summary>
        [AbpAuthorize(AppPermissions.Pages_Bom_Cartypes_Edit)]
        public virtual async Task UpdateCartypeAsync(CartypeEditDto input)
        {
            //TODO:更新前的逻辑判断，是否允许更新
            await CheckCartypeIfAlreadyExists(input.CartypeName, input.CartypeCode, input.Id);
            var entity = await _cartypeRepository.GetAsync(input.Id.Value);
            input.MapTo(entity);

            await _cartypeRepository.UpdateAsync(entity);
        }

        /// <summary>
        /// 删除车型信息
        /// </summary>
        [AbpAuthorize(AppPermissions.Pages_Bom_Cartypes_Delete)]
        public async Task DeleteCartypeAsync(EntityDto<int> input)
        {
            //TODO:删除前的逻辑判断，是否允许删除
            await _cartypeRepository.DeleteAsync(input.Id);
        }

        /// <summary>
        /// 批量删除车型信息
        /// </summary>
        [AbpAuthorize(AppPermissions.Pages_Bom_Cartypes_Delete)]
        public async Task BatchDeleteCartypeAsync(List<int> input)
        {
            //TODO:批量删除前的逻辑判断，是否允许删除
            await _cartypeRepository.DeleteAsync(s => input.Contains(s.Id));
        }

        private async Task CheckCartypeIfAlreadyExists(string cartypeName, string cartypeCode, int? id = null)
        {
            var existingCartype = await _cartypeRepository.GetAll()
                .FirstOrDefaultAsync(l => l.CartypeName == cartypeName || l.CartypeCode == cartypeCode);
            if (existingCartype == null)
            {
                return;
            }
            if (id != null && existingCartype.Id == id)
            {
                return;
            }
            throw new UserFriendlyException(L("ThiscartypeAlreadyExists"));
        }

        #endregion 车型信息管理

        #region 车型信息的Excel导出功能

        public async Task<FileDto> GetCartypeToExcel()
        {
            var entities = await _cartypeRepository.GetAll().ToListAsync();

            var dtos = entities.MapTo<List<CartypeListDto>>();

            var fileDto = _cartypeListExcelExporter.ExportCartypeToFile(dtos);

            return fileDto;
        }

        #endregion 车型信息的Excel导出功能
    }
}